package cn.itsource.minio.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.itsource.minio.service.MinioService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class MinioServiceImpl implements MinioService {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.access-key}")
    private String accessKey;

    @Value("${minio.secret-key}")
    private String secretKey;

    @Value("${minio.bucket}")
    private String bucket;

    public MinioClient getMinioClient() {
        // 构建一个Minio客户端
        return MinioClient.builder()
                //创建容器时指定的账号
                .credentials(accessKey, secretKey)
                //上传地址
                .endpoint(endpoint).build();
    }


    @Override
    public String upload(MultipartFile file) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 构建一个Minio客户端
        MinioClient minioClient = getMinioClient();
        //获取文件名
        String filename = file.getOriginalFilename();
        //获取随机文件名  FileUtil.getSuffix(filename)获取文件后缀
        String newFilename = System.currentTimeMillis() + "." + FileUtil.getSuffix(filename);
        PutObjectArgs putObjectArgs = null; //文件流，以及大小，-1代表不分片
        try {
            putObjectArgs = PutObjectArgs.builder()
                    .object(newFilename)    //文件名
                    .contentType(file.getContentType())    //文件类型
                    .bucket(bucket)  //存储目录名
                    .stream(file.getInputStream(), file.getSize(), -1).build();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //执行上传
        minioClient.putObject(putObjectArgs);
        //放回图片上传地址
        String url = endpoint + "/" + bucket + "/" + newFilename;
        return url;
    }

    /**
     * 删除附件
     */
    @Override
    public void delete(String objectName) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        MinioClient minioClient = getMinioClient();


        minioClient.removeObject(bucket,objectName);
    }
}
